package com.fuint.common.util;

import jakarta.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Servlet工具类
 * 用于处理Jakarta Servlet API与第三方库的兼容性问题
 *
 * Created by FSQ
 * CopyRight https://www.fuint.cn
 */
public class ServletUtil {

    /**
     * 读取HttpServletRequest中的数据
     * 替代IJPay的HttpKit.readData方法，因为该方法还不支持Jakarta Servlet API
     *
     * @param request HttpServletRequest
     * @return 请求体数据
     */
    public static String readData(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            throw new RuntimeException("读取请求数据失败", e);
        }
        return sb.toString();
    }

    /**
     * 将HttpServletRequest转换为Map
     * 替代AliPayApi.toMap方法，因为该方法还不支持Jakarta Servlet API
     *
     * @param request HttpServletRequest
     * @return 参数Map
     */
    public static Map<String, String> toMap(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String paramName = parameterNames.nextElement();
            String paramValue = request.getParameter(paramName);
            params.put(paramName, paramValue);
        }
        return params;
    }
}